//
//  HTMineViewController.m
//  TruckDriver
//
//  Created by Ting Han on 2017/9/26.
//  Copyright © 2017年 Ting Han. All rights reserved.
//

#import "HTMineViewController.h"
#import "HTMineViewCell.h"
#import "HTCopilotManageViewController.h"
#import "HTChangeTruckViewController.h"
#import "HTGoodsRecordsViewController.h"
#import "HTRegisterDriverInfoVC.h"
#import "HTWaybillHomeViewController.h"
#import "HTLoginVC.h"
#import "HTNotificationVC.h"
#import "UIImageView+WebCache.h"
#import "AppDelegate.h"
#import "HTHomePageViewController.h"
#import "BaseNavigationController.h"

@interface HTMineViewController ()<UITableViewDelegate,UITableViewDataSource>
#pragma mark -- header认证后

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *firstTapCenterX;
@property (strong, nonatomic) IBOutlet UIView *headerViewAfter;

@property (weak, nonatomic) IBOutlet UIImageView *headImageView;
@property (weak, nonatomic) IBOutlet UILabel *checkMessageLabel;

@property (weak, nonatomic) IBOutlet UIImageView *licenseImageView;
@property (weak, nonatomic) IBOutlet UILabel *licenseNumberLabel;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;

@property (weak, nonatomic) IBOutlet UILabel *isMastorLabel;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topSafeHeight;
@property (weak, nonatomic) IBOutlet UIView *firstTapView;
@property (weak, nonatomic) IBOutlet UIView *secondTapView;
@property (weak, nonatomic) IBOutlet UIView *lineView;
@property (weak, nonatomic) IBOutlet UIButton *firstTapButton;
@property (weak, nonatomic) IBOutlet UIButton *secondTapButton;

#pragma mark --- header 认证前

@property (strong, nonatomic) IBOutlet UIView *headerViewBefore;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *safeBottomHead;

@property (weak, nonatomic) IBOutlet UIImageView *logoImageView;

@property (weak, nonatomic) IBOutlet UILabel *messageLabel;
@property (weak, nonatomic) IBOutlet UIButton *toRegisterButton;

#pragma mark -- main
@property (weak, nonatomic) IBOutlet UITableView *tableview;
@property (nonatomic,copy) HTMineModel *mineModel;
@property (nonatomic,strong) NSArray *dataSource;
@property (nonatomic,assign) CGFloat headerTableHeight;

@end

@implementation HTMineViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"我的";
    [self configTableView];
    self.headImageView.layer.masksToBounds = YES;
    self.headImageView.layer.cornerRadius = kWidth(40);
    self.checkMessageLabel.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(didRegister:)];
    [self.checkMessageLabel addGestureRecognizer:tap];
}
- (void)configTableView{
    self.dataSource = @[@"我的运单",@"我的消息",@"检查版本",@"退出登录"];
    self.tableview.delegate = self;
    self.tableview.dataSource =self;
    self.tableview.rowHeight = kWidth(55);
    [self.tableview registerNib:[UINib nibWithNibName:@"HTMineViewCell" bundle:nil] forCellReuseIdentifier:MineViewCell];
    self.headerTableHeight = 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (self.mineModel == nil || self.mineModel.regist == nil) {
        self.headerTableHeight = 0;
        return 0;
    }
    //regist :0 为认证，1认证中 2 通过 3 不通过
    if ([self.mineModel.regist integerValue] == 2) {
        self.headerTableHeight = 330;
        return 330;
    }else{
        self.headerTableHeight = 300;
        return 300;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (self.mineModel == nil || self.mineModel.regist == nil) {
        return nil;
    }
    //regist :0 为认证，1认证中 2 通过 3 不通过
    if ([self.mineModel.regist integerValue] == 2) {
        return self.headerViewAfter;
    }else{
        return self.headerViewBefore;
    }
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    HTMineViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MineViewCell forIndexPath:indexPath];
    [cell.titleButton setTitle:self.dataSource[indexPath.row] forState:UIControlStateNormal];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    switch (indexPath.row) {
        case 0://我的运单
        {
            HTWaybillHomeViewController *way = [[HTWaybillHomeViewController alloc]init];
            [self.navigationController pushViewController:way animated:YES];
        }
            break;
        case 1://我的消息
        {
            HTNotificationVC *notif = [[HTNotificationVC alloc]init];
            [self.navigationController pushViewController:notif animated:YES];
        }
            break;
        case 2://检查版本
        {
            NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
            NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
            [UIAlertController alertStyleShowInController:self title:@"温馨提示" message: [NSString stringWithFormat:@"当前版本号为%@",app_Version] alertActionsBlock:^(NSMutableArray<UIAlertAction *> *alertActions) {
                [alertActions addObject:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil]];
            } completion:^{
                
            }];
        }
            break;
        case 3://退出登录
        {
            UIAlertView * alert = [[UIAlertView alloc] initWithTitle:nil message:@"确认退出登录？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            [alert show];
        }
            break;
        default:
            break;
    }
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        [HTUtils reLoginClear];
      //  [self.navigationController popViewControllerAnimated:YES];
        UIApplication *app =[UIApplication sharedApplication];
        AppDelegate *app2 = (AppDelegate *)app.delegate;
        HTHomePageViewController *home = [[HTHomePageViewController alloc]init];
        BaseNavigationController *nav = [[BaseNavigationController alloc]initWithRootViewController:home];
        app2.navController = nav;
        app2.window.rootViewController = nav;
    }
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self netLoadUserMessage];
}

- (IBAction)copilotManageBtn:(UIButton *)sender {
    if (self.mineModel == nil || self.mineModel.ismast == nil) {
        return;
    }
    if ([self.mineModel.ismast integerValue] == 0) {//主驾
        //副驾管理
        HTCopilotManageViewController *col = [[HTCopilotManageViewController alloc]init];
        [self.navigationController pushViewController:col animated:YES];
    }else{//副驾
        //解绑
        [UIAlertController alertStyleShowInController:self title:@"温馨提示" message:[NSString stringWithFormat:@"确认将与#%@#的车辆解绑？解绑后你将不能找货",self.mineModel.carids] alertActionsBlock:^(NSMutableArray<UIAlertAction *> *alertActions) {
            [alertActions addObject:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
            [alertActions addObject:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self netLoadUnbind];
            }]];
        } completion:^{
            
        }];
    }
}
- (IBAction)changeTruck:(UIButton *)sender {
    //更换车辆
    if (self.mineModel == nil) {
        return;
    }
    HTChangeTruckViewController *col = [[HTChangeTruckViewController alloc]init];
    col.mineModel = self.mineModel;
    [self.navigationController pushViewController:col animated:YES];
}
- (void)didRegister:(id)sender{
    if (self.mineModel == nil) {
        [HTShowUtil showMessage:@"个人资料获取失败"];
        return;
    }
    HTRegisterDriverInfoVC *dri = [[HTRegisterDriverInfoVC alloc]init];
    dri.mineModel = self.mineModel;
    [self.navigationController pushViewController:dri animated:YES];
    
}
- (IBAction)toRegistAction:(id)sender {
    if (self.mineModel == nil || [self.mineModel.regist integerValue] == 2 ) {
        return;
    }
    HTRegisterDriverInfoVC *dri = [[HTRegisterDriverInfoVC alloc]init];
    dri.mineModel = self.mineModel;
    [self.navigationController pushViewController:dri animated:YES];
   
}
#pragma mark --- 网络请求
- (void)netLoadUnbind{
    [self startHud];
    [HTHttpRequestManager requestUnbindCopilotsWithID:self.mineModel.driverid success:^(id  _Nullable responseObject) {
        [self endHud];
        DBLog(@"解绑：%@",responseObject);
        if (!responseObject) {
            [HTShowUtil showMessage:@"解绑失败"];
            return ;
        }
        NSString *codeStr = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
        if (![codeStr isEqualToString:@"200"]) {
            [HTShowUtil showMessage:@"解绑失败"];
            return;
        }
        [self netLoadUserMessage];
    } failure:^(NSError * _Nonnull error) {
        [self endHud];
        [HTShowUtil showMessage:@"解绑失败"];
    }];
}

- (void)netLoadUserMessage{
    [self startHud];
    [HTHttpRequestManager requestUserMessageSuccess:^(id  _Nullable responseObject) {
        [self endHud];
        DBLog(@"个人信息：%@",responseObject);
        if (!responseObject) {
            [HTShowUtil showMessage:@"获取失败"];
            return ;
        }
        NSString *codeStr = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
        if (![codeStr isEqualToString:@"200"]) {
            [HTShowUtil showMessage:@"获取失败"];
            return;
        }
        self.mineModel = [HTMineModel mj_objectWithKeyValues:responseObject[@"data"]];
        [self.tableview reloadData];
    } failure:^(NSError * _Nonnull error) {
        [self endHud];
        [HTShowUtil showMessage:@"获取失败"];
    }];
}
- (void)setMineModel:(HTMineModel *)mineModel{
    _mineModel = mineModel;
      //regist :0 为认证，1认证中 2 通过 3 不通过
    if ([mineModel.regist integerValue] == 2) {//认证成功
        self.nameLabel.text = mineModel.name;
        if ([mineModel.ismast isEqualToString:@"0"]) {
            self.isMastorLabel.text = @"[主驾]";
            self.firstTapCenterX.constant = kHTScreenWidth/16.0;
            self.secondTapView.hidden = NO;
            self.lineView.hidden = NO;
            [self.firstTapButton setTitle:@"副驾管理" forState:UIControlStateNormal];
        }else{
            self.isMastorLabel.text = @"[副驾]";
            self.firstTapCenterX.constant = kHTScreenWidth/4.0;
            self.secondTapView.hidden = YES;
            self.lineView.hidden = YES;
            [self.firstTapButton setTitle:@"解绑车辆" forState:UIControlStateNormal];
        }
        if ([mineModel.numbertype isEqualToString:@"1"]) {
            //blue
            self.licenseImageView.image = [UIImage imageNamed:@"bg_license_blue"];
        }else{
            self.licenseImageView.image = [UIImage imageNamed:@"bg_license_yellow"];
        }
        [self.headImageView sd_setImageWithURL:[NSURL URLWithString:mineModel.picurl] placeholderImage:[UIImage imageNamed:@"bg_headsculpture"]options:SDWebImageRefreshCached];
        if (mineModel.carids == nil || mineModel.carids.length <= 3) {
              self.licenseNumberLabel.text = mineModel.carids;
        }else{
            NSMutableString* str1=[[NSMutableString alloc]initWithString:mineModel.carids];
            [str1 insertString:@"·"atIndex:2];
            self.licenseNumberLabel.text = str1;
        }
       
    }else{//未认证成功
        self.messageLabel.text = mineModel.driverresult;
        if ([mineModel.regist integerValue] == 0) {//未认证
            self.toRegisterButton.enabled = YES;
            [self.toRegisterButton setTitle:@"去认证" forState:UIControlStateNormal];
        }else if([mineModel.regist integerValue] == 1){//认证中
            self.toRegisterButton.enabled = NO;
            [self.toRegisterButton setTitle:@"认证中" forState:UIControlStateNormal];
        }else if([mineModel.regist integerValue] == 3){//认证不通过
            self.toRegisterButton.enabled = YES;
            [self.toRegisterButton setTitle:@"修改信息" forState:UIControlStateNormal];
        }
    }
}
@end


